package no.endelighelg.app;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class JsonVenueAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private JSONArray json = null;
	
	static class ViewHolder {
		TextView title;
		TextView address;
	}
	
	public JsonVenueAdapter(Context context, JSONArray json) {
		this.inflater = LayoutInflater.from(context);
		this.json = json;
	}
	
	@Override
	public int getCount() {
		if (this.json == null)
			return 0;
		return this.json.length();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.list_item, null);
			
			holder = new ViewHolder();
			holder.title = (TextView)convertView.findViewById(R.id.list_item_title);
			holder.address = (TextView)convertView.findViewById(R.id.list_item_address);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		//if (channelMap.containsKey(position) == true) {
		if (json.isNull(position) == false) {
			try {
    			JSONObject obj = json.getJSONObject(position);
				holder.title.setText(obj.getString("title"));
				holder.address.setText(obj.getString("address"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return convertView;
	}

	public JSONObject getJSONObject(int position) {
		return this.json.optJSONObject(position);
	}
}
